using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Interfaces;

namespace Book.Blog.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IFileStorageService _fileStorageService;
        private static readonly string[] AllowedImageExtensions = { ".jpg", ".jpeg", ".png", ".gif" };

        public FilesController(IFileStorageService fileStorageService)
        {
            _fileStorageService = fileStorageService;
        }

        /// <summary>
        /// 上传文件（需登录）
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <param name="directory">目标目录（可选）</param>
        /// <returns>文件上传结果</returns>
        [HttpPost("upload")]
        [Authorize]
        public async Task<ActionResult<FileUploadResultDTO>> UploadFile(
            IFormFile file,
            [FromQuery] string? directory = null)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("未选择文件");
            }

            var options = new FileUploadOptionsDTO
            {
                Directory = directory
            };

            using (var stream = file.OpenReadStream())
            {
                var result = await _fileStorageService.SaveFileAsync(
                    stream,
                    file.FileName,
                    file.ContentType,
                    options);

                return result;
            }
        }

        /// <summary>
        /// 上传图片（需登录）
        /// </summary>
        /// <param name="file">上传的图片文件</param>
        /// <param name="generateThumbnail">是否生成缩略图</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        /// <param name="quality">图片质量</param>
        /// <param name="directory">目标目录（可选）</param>
        /// <returns>图片上传结果</returns>
        [HttpPost("upload-image")]
        [Authorize]
        public async Task<ActionResult<ImageUploadResultDTO>> UploadImage(
            IFormFile file,
            [FromQuery] bool generateThumbnail = true,
            [FromQuery] int maxWidth = 1920,
            [FromQuery] int maxHeight = 1080,
            [FromQuery] int quality = 80,
            [FromQuery] string? directory = null)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("未选择文件");
            }

            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!AllowedImageExtensions.Contains(extension))
            {
                return BadRequest("不支持的图片格式");
            }

            var options = new FileUploadOptionsDTO
            {
                GenerateThumbnail = generateThumbnail,
                MaxWidth = maxWidth,
                MaxHeight = maxHeight,
                Quality = quality,
                Directory = directory
            };

            using (var stream = file.OpenReadStream())
            {
                var result = await _fileStorageService.SaveImageAsync(
                    stream,
                    file.FileName,
                    file.ContentType,
                    options);

                return result;
            }
        }

        /// <summary>
        /// 删除文件（需登录）
        /// </summary>
        /// <param name="fileUrl">文件URL</param>
        /// <returns>无内容</returns>
        [HttpDelete]
        [Authorize]
        public async Task<ActionResult> DeleteFile([FromQuery] string fileUrl)
        {
            await _fileStorageService.DeleteFileAsync(fileUrl);
            return NoContent();
        }
    }
} 